package com.damai.aop.impl;

import java.lang.reflect.Method;

import com.citywithincity.api.ApiConfig;
import com.damai.aop.MethodCaller;
import com.damai.utils.CtClassBuilder;
import com.damai.utils.CtMethodBuilder;
import com.damai.utils.LogUtil;

import javassist.CannotCompileException;
import javassist.NotFoundException;

public class MethodCallerBuilder {

	public static MethodCaller make(Method clazz, Method method) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException {
		CtClassBuilder builder = new CtClassBuilder(clazz.getName() + method.getName() + "Caller");

		builder.beginInterface(MethodCaller.class);
		StringBuilder sb = new StringBuilder();
		Class<?>[] types = method.getParameterTypes();
		int index = 0;
		for (Class<?> type : types) {
			sb.append(type.getName()).append(" p").append(index).append("=(").append(type.getName()).append(")$2[")
					.append(index).append("];\n");
			++index;
		}

		sb.append("return ((").append(clazz.getName()).append(")$1).").append(method.getName()).append("(");
		index = 0;
		for (Class<?> type : types) {
			if (index != 0) {
				sb.append(",");
			}
			sb.append("p").append(index);
			++index;
		}
		sb.append(");");

		if (ApiConfig.debug()) {
			LogUtil.log("fun is : \n %s", sb.toString());
		}

		Method method2 = MethodCaller.class.getMethods()[0];
		CtMethodBuilder methodBuilder = builder.beginMethod(method2);
		methodBuilder.setBody(sb.toString());
		builder.endMethod();
		return builder.make().newInstance();
	}
}
